package demon4;

import java.util.Arrays;

public class Heap {
    public int useSize;
    public int[] elem;
    public Heap(){
        elem=new int[11];
    }
    public void assignment(int[] arr){
        for (int i = 0; i < elem.length; i++) {
            elem[i]=arr[i];
        }
    }
    //创建大根堆
    public void createHeap(){
        for(int parent=(useSize-1-1)/2;parent>=0;parent++){
            shifDown(parent,useSize);
        }
    }
    public void swap(int x,int y){
        int temp=elem[x];
        elem[x]=elem[y];
        elem[y]=temp;
    }
    public void shifDown(int parent,int end){
        int child=parent*2+1;
        while(child<end){
            if(child+1<end&&elem[child]<elem[child+1]){
                child++;
            }
            if(elem[child]<elem[parent]){
                swap(child,parent);
                parent=child;
                child=2*parent+1;
            }
        }
    }
    public boolean isfull(){
        return elem.length==useSize;
    }
    //向堆中插入元素
    public void offer(int x){
        if(isfull()){
            elem= Arrays.copyOf(elem,2*elem.length);
        }
        elem[useSize]=x;
        useSize++;
        shifUp(useSize-1);

    }
    public void shifUp(int child){
        int parent=(child-1)/2;
        while(parent>=0){
            if(elem[child]>elem[parent]){
                swap(child,parent);
                child=parent;
                parent=(child-1)/2;
            }else{
                break;
            }
        }
    }
    //删除堆中的元素,删除队列顶置元素.
    public int poll(){
        int old=elem[0];
        swap(0,useSize-1);
        shifDown(0,useSize);
        useSize--;
        return old;
    }
}
